// 
// @Author: xzw
// @Description:
// @Version: 1.0.0
// @Date: 2021/3/11 上午9:40
// @Copyright: MIN-Group；国家重大科技基础设施——未来网络北大实验室；深圳市信息论与未来网络重点实验室
// 

const utils = require("../sqlite/utils")
const sqlite3 = require('better-sqlite3');
const fs = require("fs")

var dbFile = "identity.db"
var dbPath = ""
var passwd = "2DD29CA851E7B56E4697B0E1F08507293D761A05CE4D1B628663F411A8086D99"

var table_create  = `CREATE TABLE IF NOT EXISTS "identityinfo" (
	"name"	varchar(255) NOT NULL,
	"pubkey"	varchar(255),
	"prikey"	varchar(255),
	"pubkey_algo"	int,
	"signature_algo"int,
	"pass"	varchar(255),
	"cert"	TEXT,
	"is_default"	int DEFAULT 0,
	"prikey_raw_byte" varchar(255),
	PRIMARY KEY("name")
);`

//
// 进行数据库文件的连接测试，如果表不存在则新建数据库文件默认写入地址为~/.min/identity/identity.db
//
// @Description:
//
function OpenDefault() {
    var homePath = utils.Home()

    if (homePath[1] != null) {
        throw new Error("The project can't get the system home path!!!")
    }

    homePath[0] = homePath[0] + "/min/identity/"
    dbPath = homePath[0]

    let isExits = utils.PathExists(homePath[0])
    if (isExits[1] != null) {
        throw new Error("The sql db file can't be created!!!");
    }
    if (!isExits[0]) {
        try{
            fs.mkdirSync(dbPath, { recursive: true })
        }catch(err){
            throw new Error("The sql db file can't be created!!!")
        }
        let isExit= utils.PathExists(homePath[0])
        if (isExit[1] != null) {
            throw new Error("The sql db file was not be created!!!")
        }
    }

    let realFile = homePath[0] + dbFile
    console.log(realFile)

    
    var db
    try{ 
        db = new sqlite3(realFile, { verbose: console.log })
    }catch(err){
        throw new Error("The sql file can't be opened")
    }

    var stmt
    try{
        stmt = db.prepare(table_create)
        stmt.run();
    }catch(err){
        throw new Error("Create table fails!!!")
    }

    db.close()
}

//
// 自定义文件地址,注意要用/结尾,比如:/min/identity/
//
// @Description:
// @param filePath string
//
function Open(filePath) {
    dbPath = filePath
    let isExits= utils.PathExists(dbPath)
    if (isExits[1] != null) {
        throw new Error("The sql db file can't be created!!!")
    }
    if (!isExits[0]) {
        try{
            fs.mkdirSync(dbPath, { recursive: true })
        }catch(err){
            logger.error(err)
            throw new Error("The sql db file can't be created!!!")
        }
        let isExit= utils.PathExists(homePath[0])
        if (isExit[1] != null) {
            throw new Error("The sql db file was not be created!!!")
        }
    }
    let realFile = dbPath + dbFile

    var db
    try{ 
        db = new sqlite3(realFile, { verbose: console.log })
    }catch(err){
        throw new Error("The sql file can't be opened")
    }

    var stmt
    try{
        stmt = db.prepare(table_create)
        stmt.run();
    }catch(err){
        throw new Error("Create table fails!!!")
    }

    db.close()
}

// //设置数据库连接密码
// func SetPasswd(pass string) error {
//     if len(pass) != 64 {
//         return errors.New("Invalid length")
//     }
//     passwd = pass
//     return nil
// }
//

//
// 连接数据库
//
// @Description:
// @return *sql.DB, error
//
function GetConn() {
    var error
    var realFile = dbPath + dbFile

    var db
    try{ 
        db = new sqlite3(realFile, { verbose: console.log })
    }catch(err){
        return [null, new Error("The sql file can't be opened")]
    }

    return [db, null]
}

module.exports = {
    OpenDefault: OpenDefault,
    Open: Open,
    GetConn: GetConn
}
